from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
from rasa_sdk.events import SlotSet
import requests

class ActionIssueInvoice(Action):
    def name(self):
        return "action_issue_invoice"

    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: dict):
        amount = tracker.get_slot("amount")
        tax_rate = tracker.get_slot("tax_rate")
        if amount and tax_rate:
            # 替换为你的发票系统 API 地址和参数
            try:
                response = requests.post(
                    "http://localhost:8088/ai/rasa/issue_invoice",
                    json={"amount": amount.replace("元", ""), "tax_rate": tax_rate.replace("%", "")},
                    headers={"Authorization": "Bearer YOUR_API_TOKEN"}
                )
                if response.status_code == 200:
                    dispatcher.utter_message(text=f"发票已开具，金额为{amount}，税率为{tax_rate}。")
                else:
                    dispatcher.utter_message(text=f"发票开具失败：{response.json().get('error', '未知错误')}。")
            except Exception as e:
                dispatcher.utter_message(text=f"发票开具失败：{str(e)}。")
            return [SlotSet("amount", amount), SlotSet("tax_rate", tax_rate)]
        else:
            dispatcher.utter_message(text="抱歉，无法识别金额或税率，请重新输入。")
            return []

class ActionQueryInvoice(Action):
    def name(self):
        return "action_query_invoice"

    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: dict):
        invoice_number = tracker.get_slot("invoice_number")
        if invoice_number:
            # 替换为你的发票系统 API 地址和参数
            try:
                response = requests.get(
                    f"http://localhost:8088/ai/rasa/query_invoice/{invoice_number}",
                    headers={"Authorization": "Bearer YOUR_API_TOKEN"}
                )
                if response.status_code == 200:
                    invoice_data = response.json()
                    dispatcher.utter_message(text=f"发票编号{invoice_number}的详情：{invoice_data}。")
                else:
                    dispatcher.utter_message(text=f"查询失败：{response.json().get('error', '未知错误')}。")
            except Exception as e:
                dispatcher.utter_message(text=f"查询失败：{str(e)}。")
            return [SlotSet("invoice_number", invoice_number)]
        else:
            dispatcher.utter_message(text="抱歉，无法识别发票编号，请重新输入。")
            return []